﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using AvalonDock.Layout;
using BaseControlLibrary;
using CommonControlLibrary;
using CommonControlLibrary.Common;
using DBAccessLibrary.Model;
using QueryResource.Common;
using QueryResource.ViewModel;
using SimpleControlLibrary.Common;
using SimpleControlLibrary.UI;
using SimpleControlLibrary.ViewModel;

namespace SimpleControlLibrary
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        public MainWindow(ISplash sp)
        {
            sp.SetProgress(50, "正在加载控件……");
            InitializeComponent();

            this.Closed += MainWindowClosed;
            //this.Loaded += (o, e) =>
            //                   {
                                   sp.SetProgress(80, "正在初始化数据……");
                                   Init();
                                   sp.SetProgress(100, "加载完成……");
                                   sp.CloseSplash();
                               //};
        }
        //主界面
        public MainViewModel ViewModel { get; set; }
        //树
        public DBTreeViewModel TreeViewModel { get; set; }

          /// <summary>
          /// 初始化
          /// </summary>
          private void Init()
          {

              ViewModel = new MainViewModel(this.dbtreeview.ViewModel);
              TreeViewModel = this.dbtreeview.ViewModel;
              DataContext = this;

              ViewModel.GetActiveSqlControl = GetActiveSqlControl;
              ViewModel.GetActiveSqlPanel += GetActiveSqlControl;
              ViewModel.ShowNewWindowLoadFile = ShowNewWindowLoadFile;

              TreeViewModel.AppendSqlAction = ShowSql;
              TreeViewModel.AppendLogAction = ShowLog;
              TreeViewModel.AppendWindow = (caption, content) => ShowNewWindowLoadFile(caption, content, false);
              TreeViewModel.AppendDBInfo = ShowDBInfo;
              TreeViewModel.AppendFieldCaption = ShowFieldCaption;
              TreeViewModel.AppendSqlContent = ShowNewWindowLoadFile;

              this.sqlcontrol.ViewModel.AppendLogAction = ShowLog;
              this.sqlcontrol.ViewModel.AppendDataAction = ShowDs;

              this.gridviewcontrol.ViewModel.AppendLogAction = ShowLog;
              this.gridviewcontrol.AppendDataSucess = ShowDataSucess;
              this.gridviewcontrol.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;

           
              //初始化
              this.dbtreeview.Init();
              this.dbtreeview.ViewModel.ShowDescriptionWindows = entity =>
              {
                  AddDescriptionWindow win =
                      new AddDescriptionWindow(entity);
                  win.ShowDialog();
              };

              this.sqlcontrol.Init(true);
              this.sqlcontrol.ChangeContentAction = SqlControlContentChange;

              if (Directory.Exists(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary"))
              {
                  foreach (string file in Directory.GetFiles(System.AppDomain.CurrentDomain.BaseDirectory + "\\Temporary", "*.txt"))
                  {
                      ShowNewWindowLoadFile(System.IO.Path.GetFileName(file), File.ReadAllText(file), false);
                  }
              }

              UpdateTip();

          }

          private void SqlControlContentChange(object tag, bool isChange)
          {
              LayoutDocument dp = tag as LayoutDocument;
              if (dp != null)
              {
                  if (isChange)
                  {
                      bool isNotChange = dp.Title.IndexOf('*') < 0;
                      if (isNotChange)
                      {
                          dp.Title += "*";
                      }
                  }
                  else
                  {
                      dp.Title = dp.Title.Replace("*", "");
                  }
              }
          }
          /// <summary>
          /// 获取更新信息
          /// </summary>
          private void UpdateTip()
          {
              Func<string> action = () =>
              {
                  System.Reflection.AssemblyName name = System.Reflection.AssemblyName.GetAssemblyName(System.Reflection.Assembly.GetExecutingAssembly().Location);

                  try
                  {
                      if (UpdateHelper.IsDown(name.Version.ToString(), System.IO.Path.GetFileName(name.CodeBase)))
                      {
                          return "亲，又有新版本了，请记得更新哦。";
                      }
                      return "当前版本:" + name.Version;
                  }
                  catch
                  {
                      return "当前版本:" + name.Version;
                  }
              };
              Task<string>.Factory.FromAsync(action.BeginInvoke, action.EndInvoke, null)
                  .ContinueWith(t => this.lbUpdateInfo.InvokeEx(() =>
                                                                    {
                                                                        this.lbUpdateInfo.Text = t.Result;
                                                                    }));
          }

          /// <summary>
          /// 获取当前激活的SQL编辑框
          /// </summary>
          /// <returns></returns>
          private SQLControl GetActiveSqlControl()
          {
              SQLControl sql;
              GetActiveSqlControl(out sql);
              return sql;
          }

          private void ActionLayoutPanel(LayoutContent item)
          {
              if (item != null && !item.IsActive)
              {
                  this.dockManager.ActiveContent = item;
              }
          }
          /// <summary>
          /// 获得当前激活的 Document
          /// </summary>
          /// <returns></returns>
          private LayoutDocument GetActiveSqlControl(out SQLControl control)
          {
              LayoutDocumentPane layoutDocumentPane = this.documentSQL.Parent as LayoutDocumentPane;
              if (layoutDocumentPane != null)
              {
                  var collection = layoutDocumentPane.Children;
                  if (collection.Count == 1)
                  {
                      LayoutDocument panel = collection[0] as LayoutDocument;
                      if (panel != null)
                      {
                          SQLControl sqlControl = panel.Content as SQLControl;
                          if (sqlControl != null)
                          {
                              control = sqlControl;
                              return panel;
                          }
                      }
                  }
                  else
                  {
                      foreach (LayoutDocument panel in collection)
                      {
                          if (!panel.IsActive)
                              continue;
                          SQLControl sqlControl = panel.Content as SQLControl;
                          if (sqlControl == null) continue;
                          control = sqlControl;
                          return panel;
                      }
                  }
              }
              control = this.sqlcontrol;
              return this.documentSQL;
          }
          private GridViewControl GetNoBusyGridControl(bool isActive)
          {
              LayoutAnchorablePane group = this.documentDS.Parent as LayoutAnchorablePane;
              GridViewControl gc = null;
              if (group != null)
              {
                  List<LayoutAnchorable> removes = new List<LayoutAnchorable>();
                  foreach (LayoutAnchorable panel in group.Children)
                  {
                      GridViewControl gridcontrol = panel.Content as GridViewControl;
                      if (gridcontrol != null)
                      {
                          if (!gridcontrol.ViewModel.IsBusy)
                          {
                              if (isActive)
                              {
                                  ActionLayoutPanel(panel);
                              }
                              if (gc != null)
                              {
                                  removes.Add(panel);
                              }
                              else
                              {
                                  gc = gridcontrol;
                              }
                          }
                      }
                  }
                  removes.ForEach(o => group.Children.Remove(o));
              }
              return gc;
          }
          private void ShowNewWindowLoadFile(string title, string content, bool isFile)
          {
              LayoutDocument panel = new LayoutDocument();
              if (documentGroup.Children.FirstOrDefault(o => o.Title == title) != null)
              {
                  panel.Title = title + new Random().Next(5, 9);
              }
              else
              {
                  panel.Title = title;
              }

              SQLControl control = new SQLControl
                                       {ViewModel = {AppendLogAction = ShowLog, AppendDataAction = ShowDs}, Tag = panel};

              panel.Content = control;
              control.ChangeContentAction = SqlControlContentChange;

              this.documentGroup.Children.Add(panel);

              ActionLayoutPanel(panel);   
              if (isFile)
              {
                  control.Init(false);
                  control.LoadFile(content);
              }
              else
              {
                  control.Init(false, false);
                  control.IsNewDocument = true;
                  control.FilePath = title;
                  control.LoadText(content);
              }

              SendKeys.Press(Key.Up);


          }
          private void ShowSql(string sql, SqlControlStatus status)
          {
              //if (!this.documentSQL.IsActive)
              //{
              //    ActionLayoutPanel(documentSQL);
              //}
              //this.sqlcontrol.ViewModel.ExecAppendCmd(sql, isRun, isNewLine);

              SQLControl control;
              GetActiveSqlControl(out control);
              if (control != null)
              {
                  control.ViewModel.ExecAppendCmd(sql, status);
              }
          }

          private void ShowLog(string msg, Color errorColor)
          {
              if (errorColor != Colors.Black)
              {
                  this.InvokeEx(() =>
                                    {
                                        if (!this.documentLog.IsActive)
                                        {
                                            ActionLayoutPanel(documentLog);
                                        }
                                    });
              }
              this.logcontrol.ScrollToEnd();
              this.logcontrol.WriteLog(msg, errorColor);
          }

          private void ShowDs(string sql)
          {
              this.BeginInvokeEx(() =>
                                     {
                                         GridViewControl control = GetNoBusyGridControl(true);
                                         if (control != null)
                                         {
                                             control.DataBind(sql);
                                         }
                                         else
                                         {
                                             LayoutAnchorablePane group = this.documentDS.Parent as LayoutAnchorablePane;
                                             if (@group == null)
                                             {
                                                 GridViewControl gridcontrol = documentDS.Content as GridViewControl;
                                                 if (gridcontrol != null && gridcontrol.ViewModel.IsBusy)
                                                 {
                                                     ShowLog("正在查询中……", Colors.Blue);
                                                 }
                                                 else
                                                 {
                                                     if (gridcontrol != null)
                                                         gridcontrol.DataBind(sql);
                                                 }
                                             }
                                             else
                                             {
                                                 ////新增一个窗体
                                                 LayoutAnchorable panel = new LayoutAnchorable {Title = "数据"};

                                                 control = new GridViewControl
                                                               {
                                                                   AppendDataSucess = ShowDataSucess
                                                               };
                                                 control.ViewModel.AppendLogAction = ShowLog;
                                                 control.ViewModel.AppendSqlContent = ShowNewWindowLoadFile;

                                                 panel.Content = control;
                                                 @group.Children.Add(panel);
                                                 ActionLayoutPanel(panel);
                                                 control.DataBind(sql);
                                             }
                                         }
                                     });
          }

          private void ShowDBInfo(string ip, string dbname, string userid)
          {
              this.BeginInvokeEx(() =>
                                     {
                                         this.lbIPname.Text = "数据库IP：" + ip;
                                         this.lbDBname.Text = string.Format("数据库名称:{0}", dbname.Replace("_", "__"));
                                         this.lbUserId.Text = "当前用户:" + userid;
                                     });
          }

          private void ShowFieldCaption(string caption)
          {
              this.lbFieldName.BeginInvokeEx(() =>
                                                 {
                                                     this.lbFieldName.Text = "说明：" + caption;
                                                 });
          }

          private void ShowDataSucess(GridViewControl control)
          {
              LayoutPanel panel = control.Tag as LayoutPanel;
              if (panel != null)
              {
                  this.dockManager.ActiveContent = panel;
              }
          }



          private void OpenCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
          {
              ViewModel.FileOpenCommand.Execute(null);
          }

          private void RunCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
          {
              ViewModel.RunSqlExecuted();
          }

          private void RunCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
          {
              if (ViewModel == null)
                  return;
              e.CanExecute = ViewModel.RunSqlCanExecute();
          }

          private void SaveCommandBindingExecuted(object sender, ExecutedRoutedEventArgs e)
          {
              ViewModel.FileSaveCommand.Execute(null);
          }

          private void SaveCommandBindingCanExecute(object sender, CanExecuteRoutedEventArgs e)
          {
              if (ViewModel == null)
                  return;
              e.CanExecute = ViewModel.FileSaveCommand.CanExecute(null);
          }
          //拷贝字段名
          private void CopyFieldName_CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
          {
              ViewModel.CopyFieldNameExecuted();
          }

          private void DockManagerDocumentClosing(object sender, AvalonDock.DocumentClosingEventArgs e)
          {
              LayoutDocument document = e.Document;

              SQLControl sql = document.Content as SQLControl;
              if (sql != null)
              {
                  sql.ViewModel.AppendLogAction = null;
                  sql.ViewModel.AppendDataAction = null;
                  sql.ViewModel = null;
                  sql.RemoveFile();

              }
          }
          void MainWindowClosed(object sender, EventArgs e)
          {
              SaveDocumentContent();
              Application.Current.Shutdown(-1);
          }

          public void SaveDocumentContent()
        {
            LayoutDocumentPane layoutDocumentPane = this.documentSQL.Parent as LayoutDocumentPane;
            if (layoutDocumentPane != null)
                foreach (LayoutDocument panel in layoutDocumentPane.Children)
                {
                    if (panel.Content is SQLControl)
                    {
                        SQLControl sql = panel.Content as SQLControl;
                        if (sql.IsNewDocument)
                        {
                            string fileName = string.Empty;
                            if (panel.Title.IndexOf('*') > 0)
                            {
                                fileName = panel.Title.Replace("*", "");
                                if (fileName != "文档")
                                {
                                    fileName = "Temporary\\" + fileName;
                                }
                                sql.SaveFile(fileName);
                            }
                        }
                        else
                        {
                            //文件
                            if (File.Exists(sql.FilePath))
                            {
                                sql.SaveFile(sql.FilePath);
                            }
                        }
                    }
                }
        }

        private void BtnVerition_Click(object sender, RoutedEventArgs e)
        {
            if(BtnVerition.Content.ToString() == "DEV模式")
            {
                XmlHelper.Instance.IsSimpleControl = true;
                BtnVerition.Content = "精简模式";
            }
            else
            {
                XmlHelper.Instance.IsSimpleControl = false ;
                BtnVerition.Content = "DEV模式";
            }
            MessageBoxHelper.Show("重启程序才会生效");
        }
    }
}
